﻿using Flurl.Http;
using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pay.Service {

    /// <summary>
    ///睿享金服 网申、网贷 数据处理
    /// </summary>
    public class RXJFService : ServiceBase, IRXJFService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        private ISoupTaskService _iSoupTaskService;
        private ILogHelper _iLogHelper;
        public RXJFService(IUnitOfWork iUnitOfWork, ISoupTaskService iSoupTaskService) : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
            _iSoupTaskService = iSoupTaskService;
            _iLogHelper = IocHelper.Get<ILogHelper>("info");
        }

        /// <summary>
        /// 睿享金服 网申、网贷 数据处理
        /// </summary>
        /// <returns></returns>
        public bool RXJFDataHandle() {
            _iLogHelper.Info("睿享金服  数据处理---------开始");
            var token = GetToken();
            _iLogHelper.Info("睿享金服  登录获得token，token：" + token);
            //处理网申数据
            CreditCardHandle(token);
            //处理网贷数据
            LoanHandle(token);
            _iLogHelper.Info("睿享金服  数据处理---------结束");
            return true;
        }
        /// <summary>
        /// 信用卡申请数据处理
        /// </summary>
        /// <param name="token"></param>
        private void CreditCardHandle(string token) {
            //信用卡申请
            List<rxjf_resp_list_model> creditCardList = new List<rxjf_resp_list_model>();//所有贷款数据
            List<rxjf_resp_list_model> curCreditCardList = new List<rxjf_resp_list_model>();
            int current = 0;
            string lastHandleMobile = context.TokenTaskCreditCard.Where(o => o.Status == 3).OrderByDescending(o => o.UpdateTime).Select(o => o.Mobile).FirstOrDefault();//最后处理过的手机号
            //请求数据
            while (curCreditCardList != null) {
                current++;
                var card_resp_str = string.Format(@"https://lion-rxjf-m.i8fu.com/apis/credit/manager/station/stationCardAccessRecords/type/QUERY_TYPE_ALL?
                                                sortName=&sortStyle=&version=0.7&beginTime=&endTime=&reviewBeginTime=&reviewEndTime=&size=50&current={0}", current)
                                   .WithHeader("X-Auth-Token", token)
                                   .WithHeader("Connection", "keep-alive")
                                   .WithHeader("Accept", "application/json, text/plain, */*")
                                   .WithHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36")
                                   .WithHeader("Referer", "https://lion-rxjf-m.i8fu.com/loan-oem-apply-records")
                                   .WithHeader("Accept-Encoding", "gzip, deflate, br")
                                   .WithHeader("Accept-Language", "zh-CN,zh;q=0.9")
                                   .GetAsync().ReceiveString().Result;
                rxjf_resp_base_model<List<rxjf_resp_list_model>> card_resp = card_resp_str.ToObject<rxjf_resp_base_model<List<rxjf_resp_list_model>>>();
                if (card_resp != null && card_resp.result != null && card_resp.result.Count() > 0) {
                    curCreditCardList = card_resp.result;
                    creditCardList.AddRange(curCreditCardList);
                    if (!string.IsNullOrEmpty(lastHandleMobile) && curCreditCardList.Exists(o => o.mobile == lastHandleMobile)) {//出现已处理的手机号，说明后面的数据已经处理，不需要再请求
                        curCreditCardList = null;
                        break;
                    }
                } else {
                    curCreditCardList = null;
                }
            }

            //处理数据
            if (creditCardList != null && creditCardList.Count() > 0) {
                List<string> mobileList = creditCardList.Select(o => o.mobile).ToList();
                _iLogHelper.Info("睿享金服  获得待处理的信用卡申请数据，手机号列表：" + mobileList.ToJson());
                List<long> userIdList = context.TokenTaskCreditCard.Where(o => o.Status == 2 && mobileList.Contains(o.Mobile)).Select(o => o.UserId).ToList();
                if (userIdList != null && userIdList.Count() > 0) {
                    _iLogHelper.Info("睿享金服  信用卡申请数据，需要增加马力的UserId列表：" + userIdList.ToJson());
                    foreach (var userId in userIdList) {
                        var result = _iSoupTaskService.TaskRecive(userId, ETaskType.CreditCard).Result;
                    }
                }

            }
        }

        /// <summary>
        /// 网贷数据处理
        /// </summary>
        /// <param name="token"></param>
        private void LoanHandle(string token) {
            //贷款
            List<rxjf_resp_list_model> loanList = new List<rxjf_resp_list_model>();//所有贷款数据
            List<rxjf_resp_list_model> curLoanList = new List<rxjf_resp_list_model>();
            int current = 0;
            string lastHandleMobile = context.TokenTaskApplyLoan.Where(o => o.Status == 3).OrderByDescending(o => o.UpdateTime).Select(o => o.Mobile).FirstOrDefault();//最后处理过的手机号

            //请求数据
            while (curLoanList != null) {
                current++;
                var loan_resp_str = string.Format(@"https://lion-rxjf-m.i8fu.com/apis/loan/oem/apply/record?
                                                applyState=&callbackState=&unionId=&mobile=&oemId=&channelId=&productId=&id=&clientNo=&version=0.7&size=50&current={0}",current)
                                   .WithHeader("X-Auth-Token", token)
                                   .WithHeader("Connection", "keep-alive")
                                   .WithHeader("Accept", "application/json, text/plain, */*")
                                   .WithHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36")
                                   .WithHeader("Referer", "https://lion-rxjf-m.i8fu.com/loan-oem-apply-records")
                                   .WithHeader("Accept-Encoding", "gzip, deflate, br")
                                   .WithHeader("Accept-Language", "zh-CN,zh;q=0.9")
                                   .GetAsync().ReceiveString().Result;
                rxjf_resp_base_model<List<rxjf_resp_list_model>> loan_resp = loan_resp_str.ToObject<rxjf_resp_base_model<List<rxjf_resp_list_model>>>();
                if(loan_resp != null && loan_resp.result != null && loan_resp.result.Count() > 0) {
                    curLoanList = loan_resp.result;
                    loanList.AddRange(curLoanList);
                    if(!string.IsNullOrEmpty(lastHandleMobile) && curLoanList.Exists(o => o.mobile == lastHandleMobile)) {//出现已处理的手机号，说明后面的数据已经处理，不需要再请求
                        curLoanList = null;
                        break;
                    }
                } else {
                    curLoanList = null;
                }
            }

            //处理数据
            if(loanList != null && loanList.Count() > 0) {
                List<string> mobileList = loanList.Select(o => o.mobile).ToList();
                _iLogHelper.Info("睿享金服  获得网贷申请数据，手机号列表：" + mobileList.ToJson());
                List<long> userIdList = context.TokenTaskApplyLoan.Where(o => o.Status == 2 && mobileList.Contains(o.Mobile)).Select(o => o.UserId).ToList();
                if (userIdList != null && userIdList.Count() > 0) {
                    _iLogHelper.Info("睿享金服  网贷申请数据，需要增加马力的UserId列表：" + userIdList.ToJson());
                    foreach (var userId in userIdList) {
                        var result = _iSoupTaskService.TaskRecive(userId, ETaskType.ApplyLoan).Result;
                    }
                }

            }
        }


        /// <summary>
        /// 登陆获得Token
        /// </summary>
        /// <returns></returns>
        private string GetToken() {
            //登录
            var login_resp_str = string.Format("https://lion-rxjf-m.i8fu.com/apis/sso/login/admin/username")
                               .WithHeader("X-Auth-Token", "")
                               .WithHeader("Connection", "keep-alive")
                               .WithHeader("Accept", "application/json, text/plain, */*")
                               .WithHeader("User-Agent", " Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36")
                               .WithHeader("Referer", "https://lion-rxjf-m.i8fu.com/login")
                               .WithHeader("Origin", "https://lion-rxjf-m.i8fu.com")
                               .WithHeader("Content-Type", "application/json")
                               .WithHeader("Accept-Encoding", "gzip, deflate, br")
                               .WithHeader("Accept-Language", "zh-CN,zh;q=0.9")
                               .PostJsonAsync(new { username = "13779933645", password = "llX6805448" }).ReceiveString().Result;
            rxjf_resp_base_model<rxjf_resp_login_model> login_resp = login_resp_str.ToObject<rxjf_resp_base_model<rxjf_resp_login_model>>();
            string token = login_resp.result.token;
            return token;
        }

    }
}
